//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;

namespace Eas.WebCrawler.Common.IO {
    /// <summary>A static helper class for reading text files and possibly ignoring comments.</summary>
    /// <remarks>Some of these functions will ingore blank lines and those whose first two characters are a c#-style comment (i.e. '//').</remarks>
    public static class TextLineEnumerator {
        /// <summary>Enumerates all lines from the passed in  <see cref="System.IO.TextReader"/>.</summary>
        /// <param name="reader">The reader from which text will be read.</param>
        /// <param name="stripComments">Whether or not to strip lines starting in c#-style one-line comments ('//').</param>
        /// <param name="stripEmptyLines">Whether or not to strip empty lines.</param>
        /// <returns>An enumeration of each line in the file.</returns>
        public static IEnumerable<string> Create(System.IO.TextReader reader, bool stripEmptyLines, bool stripComments) {
            string line = reader.ReadLine();
            while (line != null) {
                if (ShouldReadLine(line,stripComments, stripEmptyLines))
                    yield return line;
                 
                line = reader.ReadLine();
            }
        }

        /// <summary>Enumerates all lines from a file with the passed in  <paramref name="fileName"/>.</summary>
        /// <param name="fileName">The name of the rtext file from with lines of text will be read.</param>
        /// <param name="stripComments">Whether or not to strip lines starting in c#-style one-line comments ('//').</param>
        /// <param name="stripEmptyLines">Whether or not to strip empty lines.</param>
        /// <returns>An enumeration of each line in the file.</returns>
        /// <remarks>The underlying <see cref="System.IO.StreamReader"/> will not close until all items have been enumerated.  This will leave a lock on the underlying file until the enumeration completes.</remarks>
        public static IEnumerable<string> Create(string fileName, bool stripEmptyLines, bool stripComments) {
            using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
                foreach(string line in Create(reader, stripEmptyLines, stripComments)){
                    yield return line;
                }
            }
        }

        private static bool ShouldReadLine(string line, bool stripComments, bool stripEmptyLines) {
            return !(   (stripEmptyLines && string.IsNullOrEmpty(line))     ||      (stripComments && line.StartsWith("\\", StringComparison.Ordinal))  );
        }

    }
}
